import { createRouter, createWebHistory, createMemoryHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { isSubApp, getRouterMode } from '@/utils/qiankun'

// 根据环境选择不同的路由模式
const createHistory = () => {
  const mode = getRouterMode()
  if (mode === 'memory') {
    // 在 qiankun 环境中使用 memory 模式，避免影响主应用路由
    return createMemoryHistory()
  }
  // 独立运行时使用 history 模式
  return createWebHistory('/')
}

const router = createRouter({
  history: createHistory(),
  routes: [
    {
      path: '/',
      name: 'main-app-demo',
      component: () => import('../views/MainAppDataDemo.vue'),
      meta: {
        title: '主应用数据交互演示'
      }
    },
    {
      path: '/home',
      name: 'home',
      component: HomeView,
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue'),
    },
   
  ],
})

// 路由守卫，用于调试路由问题
router.beforeEach((to, from, next) => {
  console.log('[子应用] 路由切换', {
    to,
    from,
    isSubApp: isSubApp(),
  })
  next()
})

// 当子应用被激活时，根据主应用传递的路径更新路由
if (isSubApp()) {
  // 监听主应用路由变化
  window.addEventListener('popstate', () => {
    const currentPath = window.location.pathname.replace('/sub2', '')
    const targetPath = currentPath || '/'

    // 如果当前路径与目标路径不一致，则导航到目标路径
    if (router.currentRoute.value.path !== targetPath) {
      router.push(targetPath)
    }
  })
}

export default router
